<template>
  <div class="container">
    <sq-header :selected="selectedHeader"></sq-header>

    <div class="course-page">
        <img :src="courseDetail.imgUrl" alt="" class="course-bg-img">
        <div class="course-page-footer">
          <div class="course-page-footer-up">
            <div class="course-page-footer-title">{{courseDetail.name}}</div>
            <div class="course-page-footer-author">
                <img :src="courseDetail.authorImgUrl">
                <div>{{courseDetail.authorName}}</div>
            </div>
          </div>
          <div class="course-page-footer-down">
            <div class="course-page-footer-desc">{{courseDetail.briefDesc}}</div>
            <div class="course-page-footer-source">来源：{{courseDetail.sourceName}}</div>
          </div>
        </div>
    </div>

    <sq-sticky>
      <mt-navbar v-model="selectedTab" class="sq-navbar">
        <mt-tab-item id="10" @click.native="scollToDesc">简介</mt-tab-item>
        <mt-tab-item id="20" @click.native="scollToAudios">节目</mt-tab-item>
        <mt-tab-item id="30" @click.native="scollToBuyinfo">购买须知</mt-tab-item>
      </mt-navbar>
    </sq-sticky>

    <div class="sq-navbar-content" id="sq-navbar-content-div">
      <section v-bind:class="[shouldToggleMoreDetail?'section-padding':'', 'content-desc']" id="sq-content-desc-section">
          <p class="stress">课程简介:</p>
          <div v-html="detailDesc">
          </div>
          <div v-bind:class="[hiddenMoreDetail?'show-more-down':'show-more-up', 'toggle-detail']" v-if="shouldToggleMoreDetail" @click="toggleMoreDetail"></div>
      </section>
      <section class="content-audios" id="sq-content-audios-section">
        <ul class="content-audios-box">
          <sq-audio-item v-for="(item, index) in courseAudios" :item="item" :key="item.id" @togglePlay="togglePlay(item)" @buyCourse="buyCourse(courseDetail)"></sq-audio-item>
        </ul>
      </section>
      <section class="content-buyinfo" id="sq-content-buyinfo-section">
          <p class="stress">购买须知:</p>
          <div v-html="courseDetail.buyNote">
          </div>
      </section>
      <section class="content-customer" id="sq-content-customer-section">
          <p class="stress">联系客服:</p>
          <div>
            如果您在使用松鼠听听的过程中遇到任何问题，请联系客服：13928940542，或者添加客服微信：13928940542，客服工作时间10：00-18：00
          </div>

          <div class="online_help">
              <button onclick="_MEIQIA('showPanel')">在线联系客服</button>
          </div>
      </section>
    </div>
    <div class="sq-footer" v-if="!courseDetail.hasBuy">
      <button class="sq-footer-try-free" @click="tryListenFree()" style="outline: none">免费试听</button>
      <button class="sq-footer-buy" @click="buyCourse(courseDetail)" style="outline: none">立即购买（¥{{courseDetail.discPrice|priceFormat}}）</button>
    </div>

    <sq-goto-top-button></sq-goto-top-button>

    <sq-buy-confirm-box v-if="showBuyConfirmBox && !islogin" @close="toggleBuyConfirmBox" @buyCourse="buyCourse(courseDetail)"></sq-buy-confirm-box>

  </div>
</template>

<script>

import Vue from 'vue'
import SqHeader from '../components/Header'
import AudioItem from '../components/AudioItem'
import Sticky from '../components/Sticky'
import BuyConfirmBox from '../components/BuyConfirm'
import GotoTopButton from '../components/GotoTopButton'
import { Navbar, TabItem, TabContainer, TabContainerItem} from 'mint-ui'
import { getCourseDetail, getCourseByCategory, getCourseAudios} from '../api/index'
import { mapGetters,mapActions } from 'vuex';
import { Toast } from 'mint-ui';
Vue.component(SqHeader.name, SqHeader);
Vue.component(AudioItem.name, AudioItem);
Vue.component(Navbar.name, Navbar);
Vue.component(Sticky.name, Sticky);
Vue.component(GotoTopButton.name, GotoTopButton);
Vue.component(TabItem.name, TabItem);
Vue.component(TabContainer.name, TabContainer);
Vue.component(TabContainerItem.name, TabContainerItem);
Vue.component(BuyConfirmBox.name, BuyConfirmBox);

var ua = navigator.userAgent.toLocaleLowerCase();

export default {
  name: 'Course',
  data () {
    return {
      selectedHeader: 1,
      selectedTab: "10",
      courseDetail: {
        hasBuy: 1
      },
      detailDesc: "",
      shouldToggleMoreDetail: false,
      hiddenMoreDetail: false,
      courseAudios: [],
      accessTime: new Date().getTime(),
      isInWeChat: /(micromessenger)/.test(ua),
      isIphone: ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1,
    }
  },
  created () {
    this.refreshData();
  },
  computed: {
    ...mapGetters([
      'channel',
      'islogin',
      'showListenBar',
      'showBuyConfirmBox',
      'playingAudioItem'
    ])
  },
  watch: {
    courseDetail: function() {
      this.updateContentMargin();
    },
    showListenBar: function() {
      this.updateContentMargin();
    },
    islogin: function(){
      // 防止刷新这个页面，refreshData调用两次
      const now = new Date().getTime();
      if(now - this.accessTime > 3000 ) {
        this.refreshData();
      }
    }
  },
  methods: {
    refreshData() {
      var that = this;
      const reg = /\/(category|course)\/(\d*)\/(.*)$/
      if (reg.test(this.$route.path)) {
        const type = RegExp.$1;
        const ID = RegExp.$2;
        const randId = RegExp.$3;
        var getDetail = getCourseDetail;
        if (type === 'category') {
            getDetail = getCourseByCategory;
            this.selectedHeader = 0;
        }
        getDetail(ID, randId).then(function(resp){
          that.courseDetail = resp.data;
          if (type === 'category') {
            console.log('/course/' + that.courseDetail.id + "/" + that.courseDetail.randId + "?categoryID=" + ID + "&from=" + that.channel);
            window._hmt.push(['_trackPageview', '/course/' + that.courseDetail.id + "/" + that.courseDetail.randId + "?categoryID=" + ID + "&from=" + that.channel ]);
          }
          that.cleanHtml();
          that.detailDesc = that.courseDetail.detailDesc;
          if(that.courseDetail.detailDesc.length > 100){
            that.detailDesc = that.courseDetail.detailDesc.substr(0, 100) + "...";
            that.shouldToggleMoreDetail = true;
            that.hiddenMoreDetail = true;
          }
          getCourseAudios(that.courseDetail.id, that.courseDetail.randId, that.channel).then(function(resp){
            that.courseAudios = resp.data;
          }).catch(function(err){
            console.log(err);
            var errMsg = err + "";
            if (!/timeout/i.test(errMsg) && window.navigator.onLine) {
              that.$router.replace('/error/404');
            }
          });
        }).catch(function(err){
          console.log(err);
          var errMsg = err + "";
          if (!/timeout/i.test(errMsg) && window.navigator.onLine) {
            that.$router.replace('/error/404');
          }
        });
      } else {
          this.$router.replace('/error/404');
      }
    },
    toggleMoreDetail() {
      if(this.hiddenMoreDetail) {
        this.detailDesc = this.courseDetail.detailDesc;
      } else {
        this.detailDesc = this.courseDetail.detailDesc.substr(0, 100) + "...";
      }
      this.hiddenMoreDetail = !this.hiddenMoreDetail;
    },
    cleanHtml() {
      if(this.courseDetail) {
        var buyNote = this.courseDetail.buyNote;
        if(buyNote) {
          buyNote = this.htmlEncodeByRegExp(buyNote);
          buyNote = buyNote.replace(/\n/g, '<br/>');
          this.courseDetail.buyNote = buyNote;
        }
        var detailDesc = this.courseDetail.detailDesc;
        if(detailDesc) {
          detailDesc = this.htmlEncodeByRegExp(detailDesc);
          detailDesc = detailDesc.replace(/\n/g, '<br/>');
          this.courseDetail.detailDesc = detailDesc;
        }
      }
    },
    htmlEncodeByRegExp:function (str){
      var s = "";
      if(str.length == 0) return "";
      s = str.replace(/&/g,"&amp;");
      s = s.replace(/</g,"&lt;");
      s = s.replace(/>/g,"&gt;");
      s = s.replace(/ /g,"&nbsp;");
      s = s.replace(/\'/g,"&#39;");
      s = s.replace(/\"/g,"&quot;");
      return s;
    },
    updateContentMargin() {
      var contentElement = window.document.getElementById('sq-navbar-content-div');
      if(!contentElement){
        return;
      }
      var showBuyBar = !this.courseDetail.hasBuy;
      var marinBottomPX = 0;
      if (this.showListenBar) {
        marinBottomPX = 44;
      }
      if(showBuyBar) {
        contentElement.style.marginBottom =  (marinBottomPX + 44) + 'px';
        this.$store.dispatch("toggleBuyBarItem", {
          showBuyBar: true
        });
      } else {
        contentElement.style.marginBottom = marinBottomPX + 'px';
        this.$store.dispatch("toggleBuyBarItem", {
          showBuyBar: false
        });
      }
    },
    buyCourse(item) {
      const courseId = item.id;
      const randId = item.randId;
      //const islogin = this.$store.getters.islogin;
      //if(!islogin) {
      //  window._hmt.push(['_trackEvent', '订单', '登录', '课程号：' + courseId]);
      //  this.$store.dispatch("toggleLoginBox");
      //  return;
      //}
      if(window.navigator.onLine === false) {
        Toast({
          message: '网络异常，请检查网络连接',
          duration: 2000,
          className: 'custom-toast'
        });
        return;
      }
      window._hmt.push(['_trackEvent', '订单', '确认', '课程号：' + courseId]);
      var now = (new Date()).getTime();
      // 这里跳转在ios下面微信支付可能存在问题，url路径没有变化，可能不在授权目录里
      if (this.isIphone && this.isInWeChat) {
        var href = location.protocol + "//" + location.host + "/buy/" +  + courseId + "?randId=" + randId + "&accessTime=" + now;
        if ( this.channel ) {
           href = href + "&from=" + this.channel;
        }
        location.href = href;
      } else {
        this.$router.push("/buy/" + courseId + "?randId=" + randId + "&accessTime=" + now);
      }

    },
    togglePlay(audioItem) {
      audioItem.hasListen = 1;
      this.$store.dispatch("togglePlayAudioItem", {
        playingAudioItem: audioItem,
        playingCourseAudios: this.courseAudios
      });
    },
    tryListenFree() {
      var len = this.courseAudios.length;
      for(var i=0; i<len; i++){
        var audioItem = this.courseAudios[i];
        if(audioItem.free){
          this.togglePlay(audioItem);
          break;
        }
      }
    },
    _scrollToElement(elementId, selectedTab){
      var element = window.document.getElementById(elementId);
      //获取相对位置
      var relateY = element.getBoundingClientRect().top;
      var scrollY = window.document.documentElement.scrollTop || window.document.body.scrollTop;
      // 44 是tabbar 占的高度 +1 是滚动不是很精确，可能看到边框
      var absoluteY = relateY + scrollY - 44 + 1;
      window.document.body.scrollTop = absoluteY;
      window.document.documentElement.scrollTop = absoluteY;
      // 设置滚动以后，handleScroll 更新的selectedTab可能与预期不一致
      var that = this;
      setTimeout(function(){
        that.selectedTab = selectedTab;
      }, 0);
    },
    scollToDesc() {
      this._scrollToElement('sq-content-desc-section', '10');
    },
    scollToAudios() {
      this._scrollToElement('sq-content-audios-section', '20');
    },
    scollToBuyinfo() {
      this._scrollToElement('sq-content-buyinfo-section', '30');
    },
    _reachBottom(){
      var scrollY = window.document.documentElement.scrollTop || window.document.body.scrollTop;
      var windowHeight = window.document.documentElement.clientHeight || window.document.body.clientHeight;
      var totalHeight = window.document.documentElement.scrollHeight || window.document.body.scrollHeight;
      if( totalHeight - (windowHeight + scrollY) < 100 ){
        return true;
      }
      return false;
    },
    handleScroll() {
      var audiosElement = window.document.getElementById('sq-content-audios-section');
      var buyinfoElement = window.document.getElementById('sq-content-buyinfo-section');
      // 购买须知滚动到顶部或滚动到底部了，tab显示【购买须知】
      // 网页高度不够，购买须知可能触及不到顶部，所以添加_reachBottom判断
      if(buyinfoElement.getBoundingClientRect().top <= 45
        || this._reachBottom() ){
        this.selectedTab = "30";
      }else if(audiosElement.getBoundingClientRect().top <= 45 ){
        this.selectedTab = "20";
      }else {
        this.selectedTab = "10";
      }
    },
    ...mapActions([
      'toggleBuyConfirmBox'
    ]),
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed() {
    this.$store.dispatch("toggleBuyBarItem", {
      showBuyBar: false
    });
    window.removeEventListener('scroll', this.handleScroll);
  }
}
</script>

<style>
  div.sq-navbar {
    background-color: #f6f6f6;
    height: 44px;
    border-bottom: 1px solid #cccccc;
  }

  div.sq-navbar .mint-tab-item-label {
    font-size: 16px;
    line-height: 22px;
  }
  div.sq-navbar .mint-tab-item.is-selected {
    border-bottom: 2px solid #3385ff;
    color: #3385ff;
    margin-bottom: 0;
  }
  div.sq-navbar .mint-tab-item {
    padding: 11px 0px;
  }
</style>
<!-- custom scoped component -->
<style scoped>

  .container{
  	width: 100%;
  	height: 100%;
  	margin: 0px;
  	padding: 0px;
  }

  .course-page {
    height: 70vw;
    position: relative;
  }

  @media screen and (min-width: 769px) {
      .course-page {
        height: 300px;
      }
  }

  .course-bg-img {
    width: 100%;
    height: 100%;
  }

  .course-page-footer {
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
    height: 63px;
    background-color: rgba(0, 0, 0, 0.5);
    overflow:hidden;
    display: flex;
    flex-direction: column;
  }
  .course-page-footer-up {
    display: flex;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 10px;
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    margin-top: 8px;
    font-weight: bolder;
    color: #fff;
    min-width: 0px;
  }

  .course-page-footer-title {
    white-space:nowrap;
    text-overflow:ellipsis;
    overflow: hidden;
    text-align: left;
  }

  .course-page-footer-author {
    display: flex;
    flex: 0 0 auto;
  }

  .course-page-footer-author img {
    width: 27px;
    height: 27px;
    border-radius: 13.5px;
    margin-right: 5px;
  }

  .course-page-footer-down {
    display: flex;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 10px;
    font-size: 12px;
    margin-bottom: 8px;
    color: #ccc;
    min-width: 0px;
  }

  .course-page-footer-desc {
    white-space:nowrap;
    text-overflow:ellipsis;
    overflow: hidden;
    text-align: left;
  }

  .toggle-detail {
    margin-top: 8px;
    width: 100%;
    height: 20px;
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
  .show-more-down {
    background-image: url("../assets/down.png");
  }

  .show-more-up {
    background-image: url("../assets/up.png");
  }

  .course-page-footer-source {
    flex: 0 0 auto;
  }


  .sq-navbar-content section:not(:last-child) {
    border-bottom: 12px solid #f6f6f6;
  }

  .content-desc,.content-buyinfo,.content-customer {
    text-align: left;
    padding-left: 12px;
    padding-right: 12px;
    font-size: 14px;
    line-height: 21px;
    color: #000000;
    padding-top: 20px;
    padding-bottom: 20px;
  }

  .section-padding {
    padding-bottom: 8px;
  }

  .content-audios ul {
    margin: 0px;
    padding: 0px;
  }

  .stress {
    font-weight: bolder;
    margin: 0px;
    text-align: left;
    font-size: 16px;
    padding-bottom: 12px;
  }

  /* course content container */
  .sq-footer {
    position: fixed;
    left: 0px;
    bottom: 0px;
    height: 44px;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    border-top: 1px solid #cccccc;
  }

  .sq-footer button {
    height: 100%;
    border: 0px;
    font-size: 16px;
  }

  .sq-footer-try-free {
    flex-grow: 1;
    background-color: #ffffff;
    color: #02adea;
    width: 33%;
  }

  .sq-footer-buy {
    flex-grow: 2;
    background-color: #fe6b40;
    color: #ffffff;
    width: 67%;
  }
  .online_help {
    text-align: center;
  }
  .online_help button {
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    color: #02adea;
    border: 0px;
    background-color: #fff;
    margin-top: 10px;
  }

</style>
